package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacher> getCourseTeacherList(Long courseId) {

        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);

        List<CourseTeacher> list = courseTeacherMapper.selectList(queryWrapper);
        return list;
    }

    @Transactional
    @Override
    public void saveCourseTeacher(CourseTeacher courseTeacher) {
        //获取教师id
        Long id = courseTeacher.getId();
        if (id == null) {
            //id为null，则新增教师
            courseTeacher.setCreateDate(LocalDateTime.now());
            int insert = courseTeacherMapper.insert(courseTeacher);
            if (insert <= 0){
                XueChengPlusException.cast("添加教师失败");
            }
        }else{
            //id不为null,则为修改教师信息
            CourseTeacher ordCourseTeacher = courseTeacherMapper.selectById(id);
            BeanUtils.copyProperties(courseTeacher,ordCourseTeacher);
            int flag = courseTeacherMapper.updateById(ordCourseTeacher);
            if (flag <= 0) {
                XueChengPlusException.cast("修改教师信息失败");
            }
        }
    }

    @Transactional
    @Override
    public void deleteCourseTeacher(Long courseId, Long teacherId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId).eq(CourseTeacher::getId,teacherId);
        int flag = courseTeacherMapper.delete(queryWrapper);
        if (flag < 0){
            XueChengPlusException.cast("删除教师失败");
        }
    }
}
